package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.InventoryLoss;
import com.kang.pojo.InventoryLoss_itemInformation;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.ReturnRequest;
import com.kang.service.CategoryService;
import com.kang.service.InventoryLossService;
import com.kang.service.WarehouseService;
import com.kang.until.GeneratingPDF;
import com.vonechina.entity.page.ItemLossPage;
import com.vonechina.entity.page.LossListPage;
import com.vonechina.entity.page.LossStatisticsListPage;

/**
 * 库存报损控制层
 * @author wd
 *
 */
@Controller
@RequestMapping("inventoryLoss")
@SessionAttributes({"lossListPage","lossStatisticsListPage"})
public class InventoryLossController extends com.kang.controller.Controller {
	/**
	 * 库存报损--服务层接口
	 */
	@Resource
	private InventoryLossService inventoryLossService;
	/**
	 * 仓库服务层接口
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 类别服务层接口
	 */
	@Resource
	private CategoryService cService;
	
	/**
	 * 查询报损单
	 * @param session	会话
	 * @param model	Spring模型
	 * @param lossListPage	库存报损list（分页封装实体类）
	 * @return
	 */
	@RequestMapping("selectByWhere")
	public String selectByWhere(HttpSession session, Model model,LossListPage lossListPage) {
		initRight(session);
		if (checkRight("查看库存报损") != SUCCESS && checkRight("查看全部库存报损") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部库存报损") == SUCCESS) {
			lossListPage.setCreatePersonID(null);
		} else {
			lossListPage.setCreatePersonID(userID);
		}
		model.addAttribute("userID", userID);
		model.addAttribute("isAdd", checkRight("新增库存报损") == SUCCESS);
		model.addAttribute("isEditAll", checkRight("编辑全部库存报损") == SUCCESS);
		
		//得到总条数
		lossListPage.setRows(inventoryLossService.selectByWhereCount(lossListPage));
		model.addAttribute("lossList", inventoryLossService.selectByWhereList(lossListPage));
		lossListPage.setPageUrl("inventoryLoss/selectByWhere.do");
		model.addAttribute("page", lossListPage);
		
		return "stock/inventoryLoss/listInventoryLoss";
	}
	
	/**
	 * 根据库存报损id删除库存报损
	 * @param session	会话
	 * @param request	请求
	 * @param inventoryLossID	库存报损ID
	 * @param p_userid	用户ID
	 * @return
	 */
	@RequestMapping("deleteInventoryLossById")
	@ResponseBody
	public String deleteInventoryLossById(HttpSession session, ReturnRequest request,int inventoryLossID,int p_userid){
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (p_userid == userID && checkRight("新增库存报损") == SUCCESS) {
		} else if (checkRight("编辑全部库存报损") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		if(inventoryLossService.deleteInventoryLossById(inventoryLossID)){
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 根据报损id查询报损详情
	 * @param session	会话
	 * @param model	Spring模型
	 * @param inventorylossid	库存报损ID
	 * @return
	 */
	@RequestMapping("toEdit")
	public String toEdit(HttpSession session,Model model,Integer inventorylossid) {
		InventoryLoss loss=inventoryLossService.getInventoryLossById(inventorylossid);
		initRight(session);
		if (loss.getCreatepersonid() == userID && checkRight("新增库存报损") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部库存报损") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("itemList", inventoryLossService.listItemByInventorylossid(inventorylossid));//报损的物品列表
		model.addAttribute("loss",loss);//报损信息
		
		return "stock/inventoryLoss/editInventoryLoss";
	}
	
	/**
	 * 添加报损物品时根据仓库等信息查询物品列表
	 * @param page
	 * @return
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(ItemLossPage page) {
		AjaxResult result = new AjaxResult();
		List<ItemDetail> list = inventoryLossService.listItemDetailForLoss(page);
		result.setTotal(page.getRows());
		result.setRows(list);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 执行编辑保存报损物品及报损单信息
	 * @param session	会话
	 * @param inventoryLoss	报损信息（实体可）
	 * @param itemIds	批次ID集合
	 * @param number	物品的报损数量
	 * @param itemInformationIDs	报损的物品ID集合
	 * @param lossReasonS	物品的报损说明数组
	 * @return	JSON字符串
	 */
	@RequestMapping("executiveEditLossInfo")
	@ResponseBody
	public String executiveEditLossInfo(HttpSession session, InventoryLoss inventoryLoss, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, String[] lossReasonS) {
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (inventoryLoss.getCreatepersonid() == userID && checkRight("新增库存报损") == SUCCESS) {
		} else if (checkRight("编辑全部库存报损") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLoss.setLastmodifiedid((Integer) session.getAttribute("userID"));//最后修改人id
		int a = inventoryLossService.updateInventoryLoss(inventoryLoss);
		if (a > 0) {
			inventoryLossService.deleteItemNotInLossSingle(inventoryLoss.getInventorylossid(), itemIds);
			inventoryLossService.saveLossItemList(inventoryLoss.getInventorylossid(), itemIds, number,itemInformationIDs,lossReasonS,inventoryLoss.getWarehouseid());
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 保存信息并提交报损单
	 * @param session	会话
	 * @param inventoryLoss	报损信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	物品报损数量数组集合
	 * @param itemInformationIDs	报损物品ID数组集合
	 * @param lossReasonS	物品报损说明数组集合
	 * @return
	 */
	@RequestMapping("saveAndSubmitInventoryLoss")
	@ResponseBody
	public String saveAndSubmitInventoryLoss(HttpSession session, InventoryLoss inventoryLoss, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, String[] lossReasonS) {
		AjaxResult result = new AjaxResult();
		
		initRight(session);
		if (inventoryLoss.getCreatepersonid() == userID && checkRight("新增库存报损") == SUCCESS) {
		} else if (checkRight("编辑全部库存报损") == SUCCESS) {
		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLoss.setLastmodifiedid((Integer) session.getAttribute("userID"));//最后修改人id
		int a = inventoryLossService.updateInventoryLoss(inventoryLoss);
		if (a > 0) {
			inventoryLossService.saveAndSubmitInventoryLoss((Integer) session.getAttribute("userID"),inventoryLoss.getInventorylossid());//提交报损单
			inventoryLossService.deleteItemNotInLossSingle(inventoryLoss.getInventorylossid(), itemIds);//删除其他批次的物品
			inventoryLossService.saveLossItemList(inventoryLoss.getInventorylossid(), itemIds, number,itemInformationIDs,lossReasonS,inventoryLoss.getWarehouseid());
			inventoryLossService.submitUpdateLossAfterNumberForStock(itemIds,number);//报损提交后修改实际库存数量
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 查询仓库类别信息，去到添加报损界面
	 * @param session	会话
	 * @param model	Spring模型
	 * @return	前往添加报损页面
	 */
	@RequestMapping("toAddInventoryLoss")
	public String toAddInventoryLoss(HttpSession session,Model model) {
		initRight(session);
		if (checkRight("新增库存报损") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("isAdd", checkRight("新增库存报损") == SUCCESS);
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("userName", session.getAttribute("userName"));//当前操作人
		return "stock/inventoryLoss/addInventoryLoss";
	}
	
	/**
	 * 保存新增的报损单及所报损物品
	 * @param session	会话
	 * @param inventoryLoss	库存报损信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	报损的物品数量数组集合
	 * @param itemInformationIDs	报损的物品ID数组集合
	 * @param lossReasonS	报损物品说数组集合
	 * @return	JSON字符串
	 */
	@RequestMapping("saveNewAddInventoryLoss")
	@ResponseBody
	public String saveNewAddInventoryLoss(HttpSession session, InventoryLoss inventoryLoss, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, String[] lossReasonS) {
		AjaxResult result = new AjaxResult();
		
		if (checkRight("新增库存报损") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLoss.setLossnumber(inventoryLossService.selectMaxLossNumber());//生成报损单号
		inventoryLoss.setCreatepersonid((Integer) session.getAttribute("userID"));//创建人id
		inventoryLoss.setLastmodifiedid((Integer) session.getAttribute("userID"));//最后修改人id
		
		int a = inventoryLossService.addNewInventoryLoss(inventoryLoss);//新增
		//根据报损单号查询报损id
		Integer inventorylossid = inventoryLossService.getLossIdByLossNumber(inventoryLoss.getLossnumber());
		if (a > 0) {
			inventoryLossService.deleteItemNotInLossSingle(inventorylossid, itemIds);//删除不包括当前的物品
			inventoryLossService.saveLossItemList(inventorylossid, itemIds, number,itemInformationIDs,lossReasonS,inventoryLoss.getWarehouseid());
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 保存并提交新增的报损单及所报损物品
	 * @param session	会话
	 * @param inventoryLoss	报损信息（实体类）
	 * @param itemIds	批次ID数组集合
	 * @param number	报损物品数量数组集合
	 * @param itemInformationIDs	报损物品ID数组集合
	 * @param lossReasonS	物品说明数组集合
	 * @return	JSON字符串
	 */
	@RequestMapping("saveAndSubmitNewAddInventoryLoss")
	@ResponseBody
	public String saveAndSubmitNewAddInventoryLoss(HttpSession session, InventoryLoss inventoryLoss, Integer[] itemIds,
			Integer[] number, Integer[] itemInformationIDs, String[] lossReasonS) {
		AjaxResult result = new AjaxResult();
		
		if (checkRight("新增库存报损") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		
		inventoryLoss.setLossnumber(inventoryLossService.selectMaxLossNumber());//生成报损单号
		inventoryLoss.setCreatepersonid((Integer) session.getAttribute("userID"));//创建人id
		inventoryLoss.setLastmodifiedid((Integer) session.getAttribute("userID"));//最后修改人id
		
		int a = inventoryLossService.addNewInventoryLoss(inventoryLoss);//新增
		//根据报损单号查询报损id
		Integer inventorylossid = inventoryLossService.getLossIdByLossNumber(inventoryLoss.getLossnumber());
		if (a > 0) {
			inventoryLossService.saveAndSubmitInventoryLoss((Integer) session.getAttribute("userID"),inventorylossid);//提交报损单
			inventoryLossService.deleteItemNotInLossSingle(inventorylossid, itemIds);//删除不包括当前的物品
			inventoryLossService.saveLossItemList(inventorylossid, itemIds, number,itemInformationIDs,lossReasonS,inventoryLoss.getWarehouseid());
			inventoryLossService.submitUpdateLossAfterNumberForStock(itemIds,number);//报损提交后修改实际库存数量
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 库存报损统计报表
	 * @param session	会话
	 * @param model	Spring模型
	 * @param lossStatisticsListPage	报表查询条件（封装的分页实体类）
	 * @return	前往报表页面
	 */
	@RequestMapping("selectInventoryLossStatisticsList")
	public String selectInventoryLossStatisticsList(HttpSession session,Model model,LossStatisticsListPage lossStatisticsListPage) {
		
		initRight(session);
		if (checkRight("报损统计") != SUCCESS) {
			return "basic/noRight";
		}
		
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());//所有仓库
		model.addAttribute("categoryList", cService.listAllCategory());//所有类别
		model.addAttribute("lossStatisticsList", inventoryLossService.selectInventoryLossStatisticsList(lossStatisticsListPage));//统计表

		lossStatisticsListPage.setPageUrl("inventoryLoss/selectInventoryLossStatisticsList.do");
		model.addAttribute("page", lossStatisticsListPage);
		return "systemStatistics/inventoryLossStatistics/inventoryLossStatistics";
	}
	
	/**
	 * 打印报损单
	 * @param session	会话
	 * @param response	响应
	 * @param inventorylossid	报损ID
	 * @throws Exception	异常
	 */
	@RequestMapping("printInventoryLoss")
	public void printInventoryLoss(HttpSession session,HttpServletResponse response,Integer inventorylossid) throws Exception{
		
		InventoryLoss loss=inventoryLossService.getInventoryLossById(inventorylossid);
		List<InventoryLoss_itemInformation> itemList = inventoryLossService.listItemByInventorylossid(inventorylossid);//报损的物品列表
		
		//此方法为直接下载文件
		File file = GeneratingPDF.generateInventoryLossPDF(loss, itemList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
		
	}
	
}
